/**
 * 
 */
package org.mspring.crm.client.mvc;

import org.mspring.crm.client.AppEvents;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;

/**
 * @author Gao Youbo
 * @since 2012-3-5
 * 
 */
public class ApplicationController extends Controller {

    private ApplicationView applicationView;

    /**
     * 
     */
    public ApplicationController() {
        // TODO Auto-generated constructor stub
        registerEventTypes(AppEvents.Init);
        registerEventTypes(AppEvents.Login);
        registerEventTypes(AppEvents.Error);
        registerEventTypes(AppEvents.HidePage);
        registerEventTypes(AppEvents.TabChange);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.extjs.gxt.ui.client.mvc.Controller#initialize()
     */
    @Override
    protected void initialize() {
        // TODO Auto-generated method stub
        applicationView = new ApplicationView(this);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.extjs.gxt.ui.client.mvc.Controller#handleEvent(com.extjs.gxt.ui.client
     * .mvc.AppEvent)
     */
    @Override
    public void handleEvent(AppEvent event) {
        // TODO Auto-generated method stub
        EventType type = event.getType();
        if (type == AppEvents.Init) {
            onInit(event);
        } else if (type == AppEvents.Login) {
            onLogin(event);
        } else if (type == AppEvents.Error) {
            onError(event);
        } else if (type == AppEvents.HidePage || type == AppEvents.TabChange) {
            forwardToView(applicationView, event);
        }
    }

    protected void onError(AppEvent event) {
        System.out.println("error: " + event.<Object> getData());
    }

    private void onInit(AppEvent event) {
        forwardToView(applicationView, event);
        // service = (MailServiceAsync) Registry.get(Mail.SERVICE);
        // service.getMailFolders("darrell", new AsyncCallback<Folder>() {
        // public void onFailure(Throwable caught) {
        // Dispatcher.forwardEvent(AppEvents.Error, caught);
        // }
        //
        // public void onSuccess(Folder result) {
        // Dispatcher.forwardEvent(AppEvents.NavMail, result);
        // }
        // });

    }

    private void onLogin(AppEvent event) {
        forwardToView(applicationView, event);
    }

}
